package com.thermal.thermal_inspection.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thermal.thermal_inspection.annotation.RequireAdmin;
import com.thermal.thermal_inspection.common.CommonResponse;
import com.thermal.thermal_inspection.entity.*;
import com.thermal.thermal_inspection.service.*;
import com.thermal.thermal_inspection.service.impl.InspectionServiceImpl;
import com.thermal.thermal_inspection.vo.*;
import org.springframework.core.io.Resource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/inspection")
public class InspectionController {
    private static final Logger logger = Logger.getLogger(InspectionController.class);

    @Autowired
    InspectionService inspectionService;
    @Autowired
    AccountService accountService;
    @Autowired
    CacheService cacheService;
    @Autowired
    MapService mapService;
    @Autowired
    BatchService batchService;
    @Autowired
    ClassService classService;
    @Autowired
    UnitService unitService;
    @Value("${app.schedule-path}")
    private String scheduleDirPath;
    @Autowired
    private UtilService utilService;

    //缓存过期时间单位
    static final int timeOut = 10;
    static final TimeUnit timeUnit = TimeUnit.MINUTES;

    /**
     * 新建巡检任务模版
     */
    @PostMapping("/template")
    public CommonResponse<Inspection> addInspectionTemplate(@RequestBody InspectionTemplateVO inspectionTemplateVO){
        int  inspectionMapId = inspectionTemplateVO.getInspectionMapId();
        String inspectionName = inspectionTemplateVO.getInspectionName();
        int inspectionUserId = inspectionTemplateVO.getInspectionUserId();
        int inspectionClassId = inspectionTemplateVO.getInspectionClassId();
        List<InspectionData> inspectionDatas = inspectionTemplateVO.getInspectionDatas();

        //先查看是否存在这个inspectionName，不能重名
        if(inspectionService.existInspectionName(inspectionName)){
            logger.error("新增巡检任务模板失败，巡检任务名已存在，请更换任务名");
            return CommonResponse.createForError("新增巡检任务模板失败，巡检任务名已存在，请更换任务名");
        }

        //然后先新增inspection表，并取出inspection_id
        int rows1 = inspectionService.addInspection(inspectionName, inspectionUserId, inspectionClassId, inspectionMapId);
        if(rows1 == 0){
            logger.error("新增巡检任务模板失败名");
            return CommonResponse.createForError("新增巡检任务模板失败");
        }
        Inspection inspection = inspectionService.getInspectionByName(inspectionName);
        int inspectionId = inspection.getInspectionId();

        //然后用for循环插入inspection_data表
        for(InspectionData inspectionData:inspectionDatas){
            int inspectionGroupId = inspectionData.getInspectionGroupId();
            int mapDetailId = inspectionData.getMapDetailId();
            String inspectionDataDesc = inspectionData.getInspectionDataDesc();
            String inspectionDataName = inspectionData.getInspectionDataName();
            int rows2 = inspectionService.addInspectionData(inspectionId, inspectionGroupId, mapDetailId, inspectionDataDesc, inspectionDataName);
            if(rows2 == 0){
                logger.error("新增巡检任务模板失败名");
                return CommonResponse.createForError("新增巡检任务模板失败");
            }
        }
        logger.info("新增巡检任务模板成功");
        return CommonResponse.createForSuccess("SUCCESS", inspection);
    }
    /**
     * 查看所有任务模版
     */
    @GetMapping("/template")
    public CommonResponse<List<Inspection>> getInspectionTemplate(){
        List<Inspection> inspections = inspectionService.getAllInspectionTemplates();
        if (inspections == null){
            logger.error("获取所有任务模版失败！");
            return CommonResponse.createForError("获取所有任务模版失败！");
        }
        else {
            logger.info("获取所有任务模版成功！");
            return CommonResponse.createForSuccess(inspections);
        }
    }
    /**
     * 查看任务模版的具体详情
     */
    @GetMapping("/template/detail/{inspectionId}/{inspectionMapId}")
    public CommonResponse<List<InspectionDataVO>> getInspectionDetails(@PathVariable("inspectionId") int inspectionId
                                                                    ,@PathVariable("inspectionMapId") int inspectionMapId){
        List<InspectionDataVO> inspectionDataVOS = inspectionService.getAllInspectionDataVOs(inspectionId, inspectionMapId);
        if (inspectionDataVOS == null){
            logger.error("查看任务模版详情出错，有任务模版没有巡检点位！");
            return CommonResponse.createForError("查看任务模版详情出错！请刷新界面再试！");
        }else {
            logger.info("查看任务模版详情成功！");
            return CommonResponse.createForSuccess(inspectionDataVOS);
        }
    }
    /**
     * 分配巡检任务
     */
    @PostMapping("distribute")
    public CommonResponse<Batch> distribute(@RequestBody DistributeVO distributeVO){
        System.out.println(distributeVO);
        int inspectionLimitTime = distributeVO.getInspectionLimitTime();
        Timestamp inspectionStartTime = distributeVO.getInspectionStartTime();
        String inspectionWorkName = distributeVO.getInspectionWorkName();
        int inspectionId = distributeVO.getInspectionId();
        int inspectionWorkNumber = distributeVO.getInspectionWorkNumber();
        int inspectionWorkStatus = distributeVO.getInspectionWorkStatus();
        List<InspectionDetail> inspectionDetails = distributeVO.getInspectionDetails();
        Timestamp batchStartTime = distributeVO.getBatchStartTime();
        Timestamp batchEndTime = distributeVO.getBatchEndTime();

        //判断当前时间是否在开始时间和结束时间之前
        if (!utilService.isFutureBatch(batchStartTime,batchEndTime,inspectionStartTime)){
            logger.error("分配巡检任务失败，开始时间或结束时间在当前时间之前！");
            return CommonResponse.createForError("分配巡检任务失败，开始时间或结束时间在当前时间之前！");
        }
        //先查看是否存在这个inspectionWorkName，不能重名
        if(inspectionService.existInspectionWorkName(inspectionWorkName)){
            logger.error("分配巡检任务失败，分配的巡检任务名已存在，请更换任务名");
            return CommonResponse.createForError("分配巡检任务失败，分配的巡检任务名已存在，请更换任务名");
        }
        System.out.println(inspectionId);
        //查看分配的模板任务是否存在
        if(!inspectionService.existInspection(inspectionId)){
            logger.error("分配巡检任务失败，模板任务不存在");
            return CommonResponse.createForError("分配巡检任务失败，模板任务不存在");
        }
        //查看批次名是否重复
        if (batchService.existBatchName(distributeVO.getBatchName()))
            return CommonResponse.createForError("批次名已存在！");

        //获取批量生成的每一天的具体时间
        List<Timestamp> timestamps = InspectionServiceImpl.getDailyTimestampsWithSpecificTime(distributeVO.getBatchStartTime(), distributeVO.getBatchEndTime(), inspectionStartTime);

        List<Integer> rows = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String batchName = distributeVO.getBatchName();
        if (batchName == null || batchName.equals(""))
            batchName = "临时任务"+simpleDateFormat.format(timestamps.get(0));

        //创建每天的巡检任务
        for (Timestamp everyDayStartTime : timestamps){
            String everyDayWorkName = inspectionWorkName;
            if (distributeVO.getIsBatch() == 1)
                everyDayWorkName += simpleDateFormat.format(everyDayStartTime)+batchName;
            else
                everyDayWorkName += simpleDateFormat.format(everyDayStartTime);
            System.out.println(everyDayWorkName);
            //然后先新增inspection_work表，并取出inspection_work_id
            int rows1 = inspectionService.addInspectionWork(everyDayStartTime, inspectionLimitTime, everyDayWorkName,
                    inspectionId, inspectionWorkNumber, inspectionWorkStatus);
            if(rows1 == 0){
                logger.error("分配巡检任务失败");
                return CommonResponse.createForError("分配巡检任务失败");
            }
            InspectionWork inspectionWork = inspectionService.getInspectionWorkByName(everyDayWorkName);
            int inspectionWorkId = inspectionWork.getInspectionWorkId();
            rows.add(inspectionWorkId);

            //然后用for循环插入inspection_detail表
            for(InspectionDetail inspectionDetail:inspectionDetails){
                int inspectionDetailClass = inspectionDetail.getInspectionDetailClass();
                int inspectionDetailStatus = inspectionDetail.getInspectionDetailStatus();
                int inspectionDetailUser = inspectionDetail.getInspectionDetailUser();
                int inspectionDataId = inspectionDetail.getInspectionDataId();
                System.out.println(inspectionDataId);
                InspectionData inspectionData = inspectionService.getInspectionDataById(inspectionDataId);
                MapDetail mapDetail = mapService.getMapDetail(inspectionData.getMapDetailId());
                int rows2 = inspectionService.addInspectionDetail(inspectionWorkId, inspectionDataId, inspectionDetailClass, inspectionDetailUser,inspectionDetailStatus,
                                                inspectionData.getInspectionGroupId(),inspectionData.getMapDetailId(),inspectionData.getInspectionDataDesc(),inspectionData.getInspectionDataName(), mapDetail.getUnitId());


                if(rows2 == 0){
                    logger.error("分配巡检任务失败");
                    return CommonResponse.createForError("分配巡检任务失败");
                }
            }
        }

        //创建批次

        Batch batch = new Batch();
        batch.setIsBatch(distributeVO.getIsBatch());
        batch.setBatchEndTime(distributeVO.getBatchEndTime());
        batch.setBatchStartTime(distributeVO.getBatchStartTime());
        batch.setWorkBeginId(rows.get(0));
        batch.setWorkEndId(rows.get(rows.size()-1));
        batch.setBatchCreateTime(new Timestamp(System.currentTimeMillis()));
        batch.setBatchName(batchName);

        batchService.addBatch(batch);

        logger.info("分配巡检任务失败分配巡检任务成功");
        return CommonResponse.createForSuccess("SUCCESS", batch);
    }

    /**
     * 查看分配的巡检任务
     */
    @GetMapping("{userId}")
    public CommonResponse<List<InspectionVO>> getInspection(@PathVariable int userId){
        List<Batch> batches = batchService.getBatchOfNoBatch();
        List<InspectionVO> inspectionVOS = new ArrayList<>();
        for (Batch batch : batches){
            List<InspectionVO> inspectionVOS1 = inspectionService.getInspectionOfBatch(userId,batch.getBatchId());
            inspectionVOS.addAll(inspectionVOS1);
        }
        if (inspectionVOS == null)
            return CommonResponse.createForError("未查到任何的临时任务！");
        else
            return CommonResponse.createForSuccess(inspectionVOS);
    }

    /**
     * 查看分配的巡检任务详情
     */
    @GetMapping("/detail/{inspectionWorkId}/{userId}")
    public CommonResponse<List<InspectionDetailVO>> getInspectionDetail(@PathVariable int inspectionWorkId, @PathVariable int userId){
        List<InspectionDetailVO> inspectionDetailVOList = inspectionService.getInspectionDetail(inspectionWorkId, userId);
        if(inspectionDetailVOList.isEmpty()){
            logger.error("查看分配巡检任务失败");
            return CommonResponse.createForError("查看分配巡检任务失败");
        }
        logger.info("查看分配巡检任务成功");
        return CommonResponse.createForSuccess("查看分配巡检任务成功", inspectionDetailVOList);
    }
    /**
     * 根据nfc信息获取任务数据
     */
    @GetMapping("/data/{nfcMsg}/{userId}")
    public CommonResponse<List<InspectionDetailVO>> getInspectionDetailByNfcMsg(@PathVariable String nfcMsg,@PathVariable int userId){
        List<InspectionDetailVO> inspectionDetailVOList = inspectionService.getInspectionDetailVOByNfcMsg(nfcMsg, userId);
        if (inspectionDetailVOList ==null || inspectionDetailVOList.isEmpty()){
            return CommonResponse.createForError("没有相关的任务数据信息！");
        }
        return CommonResponse.createForSuccess(inspectionDetailVOList);
    }

    /**
     * 修改巡检任务模板
     */
    @PutMapping("/template/{inspectionId}")
    public CommonResponse<Inspection> changeInspection(@PathVariable int inspectionId, @RequestBody Inspection inspection){
        int  inspectionMapId = inspection.getInspectionMapId();
        String inspectionName = inspection.getInspectionName();
        int inspectionUserId = inspection.getInspectionUserId();
        int inspectionClassId = inspection.getInspectionClassId();

        //先判断巡检任务是否存在
        if (!inspectionService.existInspection(inspectionId)) {
            logger.error("巡检任务模板不存在");
            return CommonResponse.createForError("巡检任务模板不存在");
        }

        if(inspectionService.existInspectionName(inspectionName)){
            logger.error("巡检任务名已存在");
            return CommonResponse.createForError("巡检任务名已存在");
        }

        Inspection inspection1 = inspectionService.changeInspection(inspectionId, inspectionMapId, inspectionName, inspectionUserId, inspectionClassId);
        if(inspection1 == null){
            logger.error("修改巡检任务模板失败");
            return CommonResponse.createForError("ERROR");
        }
        logger.info("修改巡检任务模板成功");
        return CommonResponse.createForSuccess("SUCCESS", inspection1);
    }

    /**
     * 修改巡检任务数据
     */
    @PutMapping("/data/{inspectionDataId}")
    public CommonResponse<InspectionData> changeInspectionData(@PathVariable int inspectionDataId, @RequestBody InspectionData inspectionData){
        int inspectionId = inspectionData.getInspectionId();
        int inspectionGroupId = inspectionData.getInspectionGroupId();
        int mapDetailId = inspectionData.getMapDetailId();
        String inspectionDataDesc = inspectionData.getInspectionDataDesc();
        String inspectionDataName = inspectionData.getInspectionDataName();

        //先判断巡检任务数据是否存在
        if (!inspectionService.existInspectionData(inspectionDataId)) {
            logger.error("巡检任务数据不存在");
            return CommonResponse.createForError("巡检任务数据不存在");
        }

        InspectionData inspectionData1 = inspectionService.changeInspectionData(inspectionDataId, inspectionId,
                inspectionGroupId, mapDetailId, inspectionDataDesc, inspectionDataName);
        if(inspectionData1 == null){
            logger.error("修改巡检任务数据失败");
            return CommonResponse.createForError("ERROR");
        }
        logger.info("修改巡检任务数据成功");
        return CommonResponse.createForSuccess("SUCCESS", inspectionData1);
    }

    /**
     * 删除巡检任务模板,把所有分配了巡检模版任务的地方，变成-1
     */
    @DeleteMapping("/template/{inspectionId}")
    public CommonResponse<Object> deleteInspection(@PathVariable int inspectionId){
        //先判断巡检任务是否存在
        if (!inspectionService.existInspection(inspectionId)) {
            logger.error("巡检任务模板不存在");
            return CommonResponse.createForError("巡检任务模板不存在");
        }
        if (inspectionService.getInspectionWorkByInspectionId(inspectionId) != null)
            return CommonResponse.createForError("巡检任务模版正在使用，无法删除！");
        int rows = inspectionService.deleteInspection(inspectionId);
        if(rows == 0){
            logger.error("删除巡检任务模板失败");
            return CommonResponse.createForError("删除巡检任务模板失败");
        }
        logger.info("删除巡检任务模板成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 删除分配巡检任务
     */
    @DeleteMapping("/{inspectionWorkId}")
    public CommonResponse<Object> deleteInspectionWork(@PathVariable int inspectionWorkId){
        //先判断巡检任务详情是否存在
        if (!inspectionService.existInspectionWork(inspectionWorkId)) {
            logger.error("该分配巡检任务不存在");
            return CommonResponse.createForError("该分配巡检任务不存在");
        }

        int rows = inspectionService.deleteInspectionWork(inspectionWorkId);
        if(rows == 0){
            logger.error("删除分配巡检任务失败");
            return CommonResponse.createForError("删除分配巡检任务失败");
        }
        logger.info("删除分配巡检任务成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 查找用户巡查，异常，漏检，不合格数
     */
    @GetMapping("/statusNum")
    @RequireAdmin
    public CommonResponse<StatusNumVO> getStatusNum(@RequestParam int userId){
        StatusNumVO statusNumVO = inspectionService.getStatusNumVO(userId);
        //StatusNumVO statusNumVO = cacheService.getOrLoad("userIdStatus:" + userId, id -> inspectionService.getStatusNumVO(id), userId, timeOut, timeUnit);
        if(statusNumVO == null){
            logger.error("查找用户巡查，异常，漏检，不合格数失败");
            return CommonResponse.createForError("查找用户巡查，异常，漏检，不合格数失败");
        }
        logger.info("查找用户巡查，异常，漏检，不合格数成功");
        return CommonResponse.createForSuccess("SUCCESS", statusNumVO);
    }

    /**
     * 本周，本季，本月，本年未巡检数
     */
    @GetMapping("/nonInspection")
    public CommonResponse<NonInspectionVO> getNonInspection(@RequestParam int userId) {
        NonInspectionVO nonInspectionVO = inspectionService.getNonInspection(userId);
        if (nonInspectionVO == null) {
            logger.error("查找用户本周，本季，本月，本年未巡检数失败");
            return CommonResponse.createForError("查找用户本周，本季，本月，本年未巡检数失败");
        }
        logger.info("查找用户本周，本季，本月，本年未巡检数成功");
        return CommonResponse.createForSuccess("SUCCESS", nonInspectionVO);
    }

    /**
     * 提交数据
     */
    @PostMapping("/submit/{inspectionGroupId}/{inspectionDetailId}")
    public CommonResponse<Object> submitInspection(@PathVariable int inspectionGroupId, @PathVariable int inspectionDetailId,
                                                   @RequestParam("imageList") MultipartFile[] images,
                                                   @RequestParam("cheatMsg") MultipartFile cheatMsg,
                                                   @RequestParam("dataListJson") MultipartFile dataListJson) throws IOException {
        // 获取文件内容并转换成字符串
        String rawDataListStr = new String(dataListJson.getBytes());
        String dataListStr = rawDataListStr.replace("\\", "").replace("\"{", "{").replace("}\"", "}");

        // 创建 ObjectMapper 实例
        ObjectMapper objectMapper = new ObjectMapper();

        // 创建 DataListWrapper 实例来封装 dataList
        DataListWrapper dataListWrapper;
        try {
            // 将 JSON 字符串转换为 DataListWrapper 实例
            dataListWrapper = objectMapper.readValue(dataListStr, DataListWrapper.class);
        } catch (IOException e) {
            e.printStackTrace();
            // 处理解析失败的情况
            return CommonResponse.createForError("JSON解析失败");
        }

        // 提取 dataList
        List<TextVO> textVOList = dataListWrapper.getText();

        boolean isAbnormal = dataListWrapper.isAbnormal();

        int rows = inspectionService.submitInspection(inspectionDetailId, inspectionGroupId, textVOList, images, cheatMsg, isAbnormal);
        if(rows == 0){
            logger.error("提交数据失败");
            return CommonResponse.createForError("提交数据失败");
        }
        logger.info("提交数据成功");
        return CommonResponse.createForSuccess("SUCCESS", null);
    }

    /**
     * 取出保存图像（返回图片存在nginx里面的文件的http路径）
     */
    @GetMapping("/pictures/{inspectionDetailId}")
    public CommonResponse<List<String>> getPictures(@PathVariable int inspectionDetailId){
        List<String> imageList = inspectionService.getPictures(inspectionDetailId);
        if(imageList == null || imageList.isEmpty()){
            logger.error("图片列表为空");
            return CommonResponse.createForError("图片列表为空");
        }
        logger.info("查询成功");
        return CommonResponse.createForSuccess("SUCCESS", imageList);
    }

    /**
     * 获取点位数据
     */
    @GetMapping("/detailData/{inspectionGroupId}/{inspectionDetailId}")
    public CommonResponse<List<DataVO>> getDetailData(@PathVariable int inspectionGroupId, @PathVariable int inspectionDetailId){
        List<DataVO> dataVOList = inspectionService.getDetailData(inspectionGroupId, inspectionDetailId);
        if(dataVOList.isEmpty() || dataVOList == null){
            logger.error("未查询到点位数据");
            return CommonResponse.createForError("未查询到点位数据");
        }
        logger.info("查询点位数据成功");
        return CommonResponse.createForSuccess("SUCCESS", dataVOList);
    }

    /**
     * 查看所有用户今日巡查，异常，漏检，不合格数之和
     */
    @GetMapping("/allStatusNum")
    public CommonResponse<StatusNumVO> getAllStatusNum(@RequestParam int userId){
        if(!inspectionService.isAdmin(userId)){
            logger.error("非管理员，无权限查看");
            return CommonResponse.createForError("非管理员，无权限查看");
        }

        StatusNumVO statusNumVO = inspectionService.getAllStatusNumVO();
        if(statusNumVO == null){
            logger.error("查找用户巡查，异常，漏检，不合格数之和失败");
            return CommonResponse.createForError("查找用户巡查，异常，漏检，不合格数之和失败");
        }
        logger.info("查找用户巡查，异常，漏检，不合格数之和成功");
        return CommonResponse.createForSuccess("SUCCESS", statusNumVO);
    }

    /**
     * 获取所有任务批次
     */
    @GetMapping("batches")
    public CommonResponse<List<Batch>> getBatchs(){
        List<Batch> batches = batchService.getBatchs();
        if (batches == null)
            return CommonResponse.createForError("未查询到任何批次信息！");
        return CommonResponse.createForSuccess(batches);
    }

    /**
     * 查看批次内的巡检任务
     */
    @GetMapping("/{userId}/{batchId}")
    public CommonResponse<List<InspectionVO>> getInspectionOfBatch(@PathVariable("userId") int userId,
                                                                   @PathVariable("batchId") int batchId){
        List<InspectionVO> inspectionList = inspectionService.getInspectionOfBatch(userId,batchId);
        if (inspectionList == null)
            return CommonResponse.createForError("无此批次或查询不到这个批次内的信息！");
        return CommonResponse.createForSuccess(inspectionList);
    }

    /**
     * 修改巡检任务信息
     */
    @PutMapping("/inspectionWork")
    public CommonResponse<String> updateInspectionWork(@RequestBody InspectionWorkVO inspectionWorkVO){
        if (!inspectionService.existInspectionWork(inspectionWorkVO.getInspectionWorkId()))
            return CommonResponse.createForError("此巡检任务不存在！");
        if (inspectionService.getInspectionWorkById(inspectionWorkVO.getInspectionWorkId()).getInspectionWorkStatus() != 4)
            return CommonResponse.createForError("此巡检任务已完成或正在进行，无法修改!");

        Integer row = inspectionService.updateInspectionWork(inspectionWorkVO);
        if (row == 1)
            return CommonResponse.createForSuccess("巡检任务修改成功！");
        return CommonResponse.createForError("巡检任务修改失败！");
    }
    /**
     * 修改巡检任务点位数据
     */
    @PutMapping("/details")
    public CommonResponse<String> updateInspectionDetail(@RequestBody NewDetailListVO newDetailListVO){
        Integer row = inspectionService.updateInspectiondetails(newDetailListVO);
        if (row == 0)
            return CommonResponse.createForError("只有处理中和未开始的巡检任务点位才可以修改数据组！");
        if (row == 2)
            return CommonResponse.createForError("数据组不存在！");
        return CommonResponse.createForSuccess("修改成功！");
    }

    /**
     * 统计所有机组数据
     */
    @PostMapping("/statisticAllUnit")
    public CommonResponse<StatisticUnitVO> getStatisticUnit(@RequestBody StatisticsTimeVO statisticsTimeVO){
        Timestamp startDate = statisticsTimeVO.getStartDate();
        Timestamp endDate = statisticsTimeVO.getEndDate();
        StatisticUnitVO statisticUnit = inspectionService.getStatisticUnit(startDate, endDate);
        if(statisticUnit == null){
            logger.error("查询失败");
            return CommonResponse.createForError("查询失败");
        }
        logger.info("查询成功");
        return CommonResponse.createForSuccess("查询成功", statisticUnit);
    }

    /**
     * 统计某个机组所有数据
     */
    @PostMapping("/statisticUnit")
    public CommonResponse<StatisticOneUnitVO> getStatisticOneUnit(@RequestParam int unitId, @RequestBody StatisticsTimeVO statisticsTimeVO){
        Timestamp startDate = statisticsTimeVO.getStartDate();
        Timestamp endDate = statisticsTimeVO.getEndDate();
        StatisticOneUnitVO statisticOneUnitVO = inspectionService.getStatisticOneUnit(unitId, startDate, endDate);
        if(statisticOneUnitVO == null){
            logger.error("查询失败");
            return CommonResponse.createForError("查询失败");
        }
        logger.info("查询成功");
        return CommonResponse.createForSuccess("查询成功", statisticOneUnitVO);
    }

    /**
     * 统计某班组所有成员所有机组的数据
     */
    @PostMapping("/statisticAllUnitClassMember")
    public CommonResponse<List<StatisticMemberVO>> getStatisticAllUnitClassMember(@RequestParam int classId, @RequestBody StatisticsTimeVO statisticsTimeVO){
        Timestamp startDate = statisticsTimeVO.getStartDate();
        Timestamp endDate = statisticsTimeVO.getEndDate();
        List<StatisticMemberVO> statisticMemberVO = inspectionService.getStatisticAllUnitClassMember(classId, startDate, endDate);
        if(statisticMemberVO == null){
            logger.error("查询失败");
            return CommonResponse.createForError("查询失败");
        }
        logger.info("查询成功");
        return CommonResponse.createForSuccess("查询成功", statisticMemberVO);
    }

    /**
     * 上传排班表
     */
    @PostMapping("/distribute/schedule")
    public CommonResponse<String> uploadSchedule(@RequestParam("scheduleExcel") MultipartFile scheduleExcel){
        Integer row = inspectionService.uploadScheduleExcel(scheduleExcel);
        if (row == 1)
            return CommonResponse.createForSuccess("上传排班表成功！");
        return CommonResponse.createForError("上传排班表失败!");
    }
    /**
     * 按批次以及排班表分配任务
     */
    @PostMapping("/distribute/batch")
    public CommonResponse<String> distributeBatchAndSchedule(@RequestBody DistributeBatchVo distributeBatchVo){
        System.out.println(distributeBatchVo);
        System.out.println(distributeBatchVo);
        System.out.println(scheduleDirPath);
        String inspectionWorkName = distributeBatchVo.getInspectionWorkName();
        int inspectionId = distributeBatchVo.getInspectionId();
        String batchName = distributeBatchVo.getBatchName();

        //看排班表是否存在
        if (!utilService.isExistScheduleExcel())
            return CommonResponse.createForError("排班表不存在，请上传！");
        //先查看是否存在这个inspectionWorkName，不能重名
        if(inspectionService.existInspectionWorkName(inspectionWorkName)){
            logger.error("分配巡检任务失败，分配的巡检任务名已存在，请更换任务名");
            return CommonResponse.createForError("分配巡检任务失败，分配的巡检任务名已存在，请更换任务名");
        }

        //查看分配的模板任务是否存在
        if(!inspectionService.existInspection(inspectionId)){
            logger.error("分配巡检任务失败，模板任务不存在");
            return CommonResponse.createForError("分配巡检任务失败，模板任务不存在");
        }
        //查看批次名是否重复
        if (batchService.existBatchName(distributeBatchVo.getBatchName()))
            return CommonResponse.createForError("批次名已存在！");
        //判断批次名是否存在
        if (batchName == null)
            return CommonResponse.createForError("未定义批次名！");
        //判断排班表里面的班组Id是否存在
        if (!utilService.isExistClass())
            return CommonResponse.createForSuccess("排班表里面的班组不存在！");

        String msg = inspectionService.distributeInspection(distributeBatchVo);
        if (msg.equals("ABNORMAL"))
            return CommonResponse.createForError("排班表格式异常，请把开始时间和结束时间设为文本类型！");
        if (msg.equals("ERROR"))
            return CommonResponse.createForError("排班表内出现了未被创建的班组！");

        return CommonResponse.createForSuccess("创建成功！");
    }
    /**
     * 下载排班表
     */
    @GetMapping("/distribute/schedule")
    public ResponseEntity<Resource> downloadSchedule() {
        String filePath = scheduleDirPath + "/schedule.xlsx";
        File file = new File(filePath);

        // 检查文件是否存在
        if (!file.exists() || !file.isFile()) {
            return ResponseEntity.notFound().build();
        }

        // 使用 FileSystemResource 读取文件
        Resource resource =  new FileSystemResource(file);

        // 设置响应头，定义文件下载信息
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=schedule.xlsx");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .body(resource);
    }
}
